package com.simplemobiletools.camera.utils

import android.content.Context
import android.net.Uri
import android.provider.BaseColumns
import android.provider.MediaStore

class MediaUtil {
    companion object {

        fun getNewPhoto(ctx: Context, listener: MediaListener) {
            getNewMedia(ctx, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, listener)
        }

        fun getNewVideo(ctx: Context, listener: MediaListener) {
            getNewMedia(ctx, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, listener)
        }

        fun getNewAudio(ctx: Context, listener: MediaListener) {
            getNewMedia(ctx, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, listener)
        }

        fun getNewMedia(ctx: Context, uri: Uri, listener: MediaListener) {
            val lastMediaId = getLatestMediaId(ctx, uri)
            if (lastMediaId == 0L) {
                listener.notFound()
                return
            }
            listener.foundMedia(Uri.withAppendedPath(uri, lastMediaId.toString()))
        }

        fun getLatestMediaId(ctx: Context, uri: Uri): Long {
            val projection = arrayOf(
                BaseColumns._ID
            )
            val sortOrder = "${BaseColumns._ID} DESC LIMIT 1"
            try {
                val cursor = ctx.contentResolver.query(uri, projection, null, null, sortOrder)
                cursor?.use {
                    if (cursor.moveToFirst()) {
                        val columnIndex = cursor.getColumnIndex(BaseColumns._ID)
                        return cursor.getLong(columnIndex)
                    }
                }
            } catch (ignored: Exception) {
            }
            return 0
        }

    }
}
